#!/usr/bin/perl
#
# send_one.pl - simple flag sender
#

use strict;
use Socket;
use constant
{
	DEBUG		=> 0,			# 1 - print debug information
	SHOW_REMOTE_MSG	=> 0,			# 1 - show replies from remote host
	TIMEOUT		=> 5,			# Timeout for sending flag
	JURY_HOST	=> '10.0.0.37',
	JURY_PORT	=> 31337,
};

my %ret_msg = 
(
	0	=> 'internal error',
	1	=> 'flag NOT accepted, TRY later',
	2	=> 'flag NOT accepted, DO NOT TRY later',
	3	=> 'flag ACCEPTED',
);

my $MSG_SUCCESS		= 'Congratulations, you captured a flag!';
my @MSG_DONT_TRY	= ( 'Sorry, flag is your own',  'Sorry, flag expired', 'Sorry, you already submitted this flag' );

$| = 1;

$SIG{ALRM} = sub
{
	print "send_one.pl: error: timeout\n";
	exit 0;
};

sub recv_answer
{
	defined recv( S, my $answ, 10240, 0 )	or do { print "send_one.pl: error: recv failed: $!\n"; exit 0 };
	chomp $answ;
	return $answ;
}

@ARGV == 2 					or do { warn "usage: ./send_one.pl <team_id> <flag>\n"; exit 0 };
my ( $id, $flag ) = @ARGV;

print "send_one.pl: team = '$id', flag = '$flag'\n" if DEBUG;

alarm TIMEOUT;

socket( S, PF_INET, SOCK_STREAM, 0 )		or do { print "send_one.pl: error: socket failed: $!\n"; exit 0 };
my $jury_addr = inet_aton( JURY_HOST )		or do { print "send_one.pl: error: inet_aton failed: $!\n"; exit 0 };
connect( S, sockaddr_in( JURY_PORT, $jury_addr ) ) or do { print "send_one.pl: error: connect failed: $!\n"; exit 0 };

print "send_one.pl: info: connected\n"		if DEBUG;

my $answ = recv_answer( );
print "send_one.pl: recv: $answ\n" 		if SHOW_REMOTE_MSG;

defined send( S, "$id\r\n", 0 )			or do { print "send_one.pl: error: send 'team_id' failed: $!\n"; exit 0 };
$answ = recv_answer( );
print "send_one.pl: recv: $answ\n" 		if SHOW_REMOTE_MSG;

defined send( S, "$flag\r\n", 0 )		or do { print "send_one.pl: error: send 'flag' failed: $!\n"; exit 0 };
$answ = recv_answer( );

print "send_one.pl: recv: " 		if SHOW_REMOTE_MSG;
print "$answ\n";

send( S, "quit\r\n", 0 );
close( S );

if ( $answ =~ /^$MSG_SUCCESS/ )
{
	print "send_one.pl: return 3 ($ret_msg{3})\n"	if DEBUG;
	exit 3;
}

for ( @MSG_DONT_TRY )
{
	if ( $answ =~ /^$_/ )
	{
		print "send_one.pl: return 2 ($ret_msg{2})\n"	if DEBUG;
		exit 2;
	}
}

print "send_one.pl: return 1 ($ret_msg{1})\n"		if DEBUG;
exit 1;

